<?php

namespace app\common\model\xilumarket;

use think\Db;
use think\Model;
use think\Exception;
use app\common\model\User;
use function fast\array_get;
use traits\model\SoftDelete;
use app\common\model\Autoreplay;
use think\exception\PDOException;


class ProductMessage extends Model
{
    use SoftDelete;
    // 表名
    protected $name = 'xilumarket_product_message';

    protected $autoWriteTimestamp = 'int';

    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    protected $append = [
        'createtime_text'
    ];

    public static function init() {
        $updateTopicForumComment = function($row) {
            $product_id = $row->product_id;
            $count = static::where('product_id',$product_id)->count();
            Product::where('id',$product_id)->update(['message_count'=>$count]);
        };
        self::afterInsert($updateTopicForumComment);
        self::afterDelete($updateTopicForumComment);
    }

    public function getCreatetimeTextAttr($value,$data){
        if(isset($data['createtime'])){
            return xilumarket_time_cha(time(),$data['createtime']);
        }
        return '';
    }

    public function product(){
        return $this->hasOne(Product::class,'id','product_id',[],'INNER')->setEagerlyType(0);
    }

    public function user() {
        return $this->belongsTo(User::class, 'user_id')->setEagerlyType(0);
    }

    public function puser(){
        return $this->hasOne(User::class,'id','puser_id',[],'LEFT')->setEagerlyType(0);
    }

    public function childrenMessage(){
        return $this->hasMany(self::class,'top_id','id');
    }

    public static function addMessage($params) {
        $pid = array_get($params,'pid');
        if($pid){
            $pmessage = self::where('id',$pid)->field('user_id,top_id')->find()?:[];
            $params['puser_id'] = $pmessage ? $pmessage['user_id'] : 0;
            $params['top_id'] = empty($pmessage['top_id']) ? $pid : $pmessage['top_id'];
        }
        //判断是否需要审核
        $params['status'] = 1;
        $shopinfo = Config::getMyConfig('shopinfo');
        if($shopinfo && $shopinfo['message_switch'] == 0){
            $params['status'] = 2;
        }else{
            $params['status'] = 1;
        }
        try {
            $comment = new self();
            $product = Product::find($params['product_id']);
            $keys = Autoreplay::where(['type' => 'product', 'user_id' => $product->user_id])->select();
            $params['content'] = array_get($params,'content', '');
            $replay = auto_replay($params['content'], $keys, 'key', false);
            if($replay) {
                $params['comment_count'] = 1;
            }
            check_sens_word($params['content']);
            $ret = $comment->allowField(true)->save($params);
            if ($ret === false) {
                throw new Exception($comment->getError());
            }
            if($replay) {
                $comment->create([
                    'pid' => $comment->id,
                    'content'   => $replay['content'],
                    'top_id' => $params['top_id'] ?? 0,
                    'user_id'   => $product->user_id,
                    'puser_id'  => $params['puser_id'],
                ]);
            }
        }catch (Exception|PDOException $e) {
            throw $e;
        }
        return $comment;
    }
}
